<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;

use app\model\UserBill as UserBillModel;
use app\lib\BceApi as BceApi;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;


class Plan extends Controller
{
    // 咨询翻译
    public function newsTrans(){
        $curtime = time();
        $list = Db::name('news')->where([
            ['status','in',[0,2]],
            ['language','=','en']
        ])->select();

        $ak = config('config.aliyun.keyId');
        $sk = config('config.aliyun.keySecret');
        AlibabaCloud::accessKeyClient($ak, $sk)
            ->regionId('cn-hangzhou')
            ->asDefaultClient()->options([
        ]);

        foreach ($list as $k => $vo) {
            // 超过5分钟，结束该脚本
            if (time() - $curtime > 280) {
                exit('end');
            }
            
            try {
                $params = [
                      'FormatType' => "text",
                      'SourceLanguage' => "en",
                      'TargetLanguage' => "zh",
                      'Scene' => "general",
                      'SourceText' => $content,
                ];
                // 判断是翻译content还是summarize
                if ( $vo['status'] == 0 ) {
                    $params['SourceLanguage'] = 'en';
                    $params['TargetLanguage'] = 'zh';
                    $params['SourceText'] = $vo['content'];
                }else{
                    $params['SourceLanguage'] = 'zh';
                    $params['TargetLanguage'] = 'en';
                    $params['SourceText'] = $vo['summarize'];
                }

                $result = AlibabaCloud::rpc()
                    ->product('alimt')
                    // ->scheme('https') // https | http
                    ->version('2018-10-12')
                    ->action('TranslateGeneral')
                    ->method('POST')
                    ->host('mt.cn-hangzhou.aliyuncs.com')
                    ->options([
                        'query' => $params,
                    ])
                    ->request();
                $result = $result->toArray();
                $save_data = [];
                if ( $result['Code'] == '200' && !empty($result['Data']['Translated']) ) {
                    if ($vo['status'] == 0) {
                        $save_data['status'] = 1;
                        $save_data['content_zh'] = $result['Data']['Translated'];
                    }else{
                        $save_data['status'] = 10;
                        $save_data['summarize_en'] = $result['Data']['Translated'];
                    }
                    
                }else{
                    // $save_data['status'] = -1;
                    $save_data['status'] = 1;
                }

                Db::name('news')->where('id',$vo['id'])->update($save_data);
            } catch (ClientException $e) {
                dump($e->getMessage());
            } catch (ServerException $e) {
                dump($e->getMessage());
            }
        }

        echo 'success';
    }

    // 调用咨询工作流，提取咨询内容
    public function newsWorkflow(){
        $curtime = time();
        $list = Db::name('news')->where([
            ['status','=',1]
        ])->select();
        $params = [
            'UserId'=>'code123456',
            'InputData'=>[]
        ];
        $api_url = 'http://hiagent.deyunai.com:32300/api/proxy/api/v1/sync_run_app_workflow';
        $api_key = 'd3ceddkij7mji2c5cqj0';
        foreach ($list as $k => $vo) {
            // 超过5分钟，结束该脚本
            if (time() - $curtime > 280) {
                exit('end');
            }
            $params['InputData'] = json_encode(['news_id'=>$vo['id'].'']);
            // echo(json_encode($params));die;
            $result = httpRequest($api_url,json_encode($params),'POST',[
                "content-type: application/json",
                'Apikey:'.$api_key
            ]);
            $result = json_decode($result,true);
            $save_data = [];
            $save_tags = [];
            if ($result['status'] == 'success') {
                $save_data['status'] = $vo['language'] == 'en' ? 2 : 10;
                $output = json_decode($result['output'],true);
                if (!empty($output['category'])) {
                    $save_data['category'] = $output['category'];
                }
                if (!empty($output['summarize'])) {
                    $save_data['summarize'] = $output['summarize'];
                }
                if (!empty($output['tags'])) {
                    $save_data['tags'] = $output['tags'];

                    $tags = json_decode($output['tags'],true);
                    foreach ($tags as $tag) {
                        $save_tags[] = [
                            'news_id'=>$vo['id'],
                            'name'=>$tag['name'],
                            'content'=>$tag['content']
                        ];
                    }
                }
                
            }else{
                $save_data['status'] = -1;
            }

            $save_data['utime'] = time();
            Db::name('news')->where('id',$vo['id'])->update($save_data);
            if (!empty($save_tags)) {
                Db::name('news_tag')->insertAll($save_tags);
            }

        }

        echo 'success';
    }

    // 创建报告
    public function createReport(){
        $curdate = date('Y-m-d');
        if ( Db::name('report')->where('cdate',$curdate)->value('id') > 0 ) {
            exit('finish');
        }

        $list = Db::name('news')->where([
            ['cdate','=',$curdate],
            ['status','>=',2]
        ])->select();
        if (empty($list)) {
            exit('empty');
        }
        $contents = [];
        foreach ($list as $k => $vo) {
            $content = [];
            $content[] = ($k+1).'.标题：'.$vo['title'];
            $content[] = '· 摘要：'.$vo['summarize'];
            $content[] = '· 来源URL：'.$vo['url'];

            $content = implode("\r\n",$content);

            $contents[] = $content;
        }

        $title = date('Y年m月d日',strtotime($curdate)).'热点资讯汇总，速览多领域重要动态';
        $save_data = [
            'cdate'=>$curdate,
            'ctime'=>time(),
            'title'=>$title,
            'content'=>implode("\r\n\r\n",$contents),
            'type'=>0
        ];
        Db::name('report')->insert($save_data);
    }


    // 调用报告工作流，获取总结
    public function reportWorkflow(){
        $curtime = time();
        $list = Db::name('report')->where([
            ['status','=',0]
        ])->select();
        $params = [
            'UserId'=>'code123456',
            'InputData'=>[]
        ];
        $api_url = 'http://hiagent.deyunai.com:32300/api/proxy/api/v1/sync_run_app_workflow';
        $api_key = 'd3dnm7vscramk9lqche0';
        foreach ($list as $k => $vo) {
            // 超过5分钟，结束该脚本
            if (time() - $curtime > 280) {
                exit('end');
            }
            $params['InputData'] = json_encode(['report_id'=>$vo['id'].'']);
            // echo(json_encode($params));die;
            $result = httpRequest($api_url,json_encode($params),'POST',[
                "content-type: application/json",
                'Apikey:'.$api_key
            ]);
            $result = json_decode($result,true);
            $save_data = [];
            if ($result['status'] == 'success') {
                $save_data['status'] = 1;
                $output = json_decode($result['output'],true);
                if (!empty($output['summarize'])) {
                    $save_data['summarize'] = $output['summarize'];
                }
            }else{
                $save_data['status'] = -1;
            }

            Db::name('report')->where('id',$vo['id'])->update($save_data);
        }
    }

}
